package com.face.console.service.impl;

import com.face.console.dao.UserDtoMapper;
import com.face.console.pojo.dto.UserDto;
import com.face.console.pojo.query.UserQuery;
import com.face.console.pojo.vo.UserVo;
import com.face.console.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * Description:
 * <p>
 * Created by Andy_Lau on 2020/12/2 0:26
 */
@Service
public class UserImpl implements UserService
{


    @Autowired
    private UserDtoMapper userDtoMapper;


    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public PageInfo<UserDto> queryUserAll() {
//        PageHelper.startPage(1, 10);
        PageInfo<UserDto> pageInfo = new PageInfo<UserDto>(userDtoMapper.selectUserAll());
        return pageInfo;
    }

    @Override
    public UserDto selectByPrimaryKey(Long id) {

        String key = "User_"+id;
        ValueOperations<String, UserDto> operations = redisTemplate.opsForValue();
        //判断redis中是否有键为key的缓存
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            UserDto user = operations.get(key);
            System.out.println("从缓存中获得数据：" + user.getUsername());
            System.out.println("------------------------------------");
            return user;
        } else {
            UserDto user = userDtoMapper.selectByPrimaryKey(id);
            System.out.println("查询数据库获得数据：" + user.getUsername());
            System.out.println("------------------------------------");
            // 写入缓存
            operations.set(key, user, 5, TimeUnit.HOURS);
            return user;
        }
    }

    @Override
    public UserVo login(UserQuery query) {
        return userDtoMapper.login(query);
    }



}
